/// 使用 File api
import 'dart:convert';
import 'dart:io';

import 'package:device_info_plus/device_info_plus.dart';
import 'package:dio/dio.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';

/// 保存文件或图片到本地
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:path/path.dart' as path;
import 'package:path_provider/path_provider.dart';

/// 授权管理
import 'package:permission_handler/permission_handler.dart';
import 'package:tiktokadult/config/address.dart';
import 'package:tiktokadult/hj_utils/global.dart';
import 'package:tiktokadult/tools_base/cache/image_cache_manager.dart';
import 'package:tiktokadult/tools_base/loading/loading_alert_widget.dart';

class ImageUtil {
  static Future<Uint8List> base64toImg(String base64Str) async {
    Uint8List bytes = base64.decode(base64Str);
    return bytes;
  }

  //拼接url
  static String realImgUrl(String imageUrl) {
    bool isGif = imageUrl.contains(".gif");
    if (imageUrl.startsWith("http") || imageUrl.startsWith("https") || isGif) {
      return imageUrl;
    } else {
      String realImgUrl = path.join(Address.baseImagePath ?? '', imageUrl);
      return realImgUrl;
    }
  }

  // 保存图片到相册
  static Future<bool> saveImageGallery({required String? imageUrl, bool isAsset = false}) async {
    /// 权限检测
    PermissionStatus storageStatus = await Permission.storage.status;
    if (storageStatus != PermissionStatus.granted) {
      storageStatus = await Permission.storage.request();
      if (storageStatus != PermissionStatus.granted) {
        throw '无法存储图片，请先授权！';
      }
    }
    if (imageUrl == null || imageUrl.isEmpty == true) return false;

    /// 保存的图片数据
    Uint8List imageBytes;
    if (isAsset == true) {
      /// 保存资源图片
      String realImgUrl = ImageUtil.realImgUrl(imageUrl);
      ByteData bytes = await rootBundle.load(realImgUrl);
      imageBytes = bytes.buffer.asUint8List();
    } else {
      LoadingAlertWidget.show();

      Map<String, String>? headers = {};
      headers['cache-control'] = 'max-age=31104000';
      File file = await ImageCacheManager().getSingleFile(imageUrl, headers: headers);
      LoadingAlertWidget.cancel();
      imageBytes = await file.readAsBytes();
    }

    // 保存图片
    final result = await ImageGallerySaver.saveImage(imageBytes);
    showToast(result != null ? '保存图片成功' : '图片保存失败,请重试');
    return true;
  }

  // 下载视频
  static saveVideoGallery(String url) async {
    AndroidDeviceInfo androidInfo = await DeviceInfoPlugin().androidInfo;
    String androidVersion = androidInfo.version.release;

    PermissionStatus status;

    if (int.parse(androidVersion) <= 12) {
      status = await Permission.storage.request();

      if (!status.isGranted) {
        showToast("请检查权限是否开启");
        return false;
      }
    } else {
      status = await Permission.photos.request();

      if (!status.isGranted) {
        showToast("请检查权限是否开启");
        return false;
      }
    }

    /// 权限检测
    if (status != PermissionStatus.granted) {
      status = await Permission.storage.request();
      if (status != PermissionStatus.granted) {
        throw '无法存储视频，请先授权！';
      }
    }
    var appDocDir = await getTemporaryDirectory();
    String savePath = appDocDir.path + "/temp.mp4";
    LoadingAlertWidget.show();
    try {
      LoadingAlertWidget.showExchangeTitle("正在上传下载视频...");
      await Dio().download(
        url,
        savePath,
        onReceiveProgress: (count, total) {
          LoadingAlertWidget.showExchangeTitle(
            "正在下载视频${(100 * count / total).toStringAsFixed(1)}%",
          );
        },
      );
      LoadingAlertWidget.showExchangeTitle("正在保存视频...");
      final result = await ImageGallerySaver.saveFile(savePath);
      print(result);
      if (result["isSuccess"]) {
        showToast("保存视频成功");
      } else {
        showToast("保存视频失败");
      }
    } catch (e) {
      showToast(e.toString());
    } finally {
      LoadingAlertWidget.cancel();
    }
  }

  /// 保存数据到相册
  static Future<bool> savePngDataToAblumn(Uint8List? pngBytes) async {
    if (pngBytes == null) return false;

    AndroidDeviceInfo androidInfo = await DeviceInfoPlugin().androidInfo;
    String androidVersion = androidInfo.version.release;

    PermissionStatus status;

    if (int.parse(androidVersion) <= 12) {
      status = await Permission.storage.request();

      if (!status.isGranted) {
        showToast("请检查权限是否开启");
        return false;
      }
    } else {
      status = await Permission.photos.request();

      if (!status.isGranted) {
        showToast("请检查权限是否开启");
        return false;
      }
    }

    /// 权限检测
    if (status != PermissionStatus.granted) {
      status = await Permission.storage.request();
      if (status != PermissionStatus.granted) {
        throw '无法存储图片，请先授权！';
      }
    }
    var map = await ImageGallerySaver.saveImage(pngBytes);
    if (null != map && map["isSuccess"] == true) {
      showToast("图片保存成功");
      return true;
    } else {
      showToast("保存失败，请手动截图");
      return false;
    }
  }
}
